import on from '@feidao-factory/core/on';
import z_index from './z-index';

/**
 * 提示框
 * @param content 提示的内容
 * @param title 标题上的文字
 * @param btn_label 按钮文字
 * @param background 背景颜色，默认为：#1890ff
 * @example alert(content, title, btn_label);
 */
export default function alert(content: string, title: string, btn_label: string, background = '#1890ff') {
	const icon_close = '<img style="width:20px;height:20px" src="" />';
	const html = `<div style="background:rgba(0,0,0,.3);height:100%;width:100%;position:fixed;top:0;left:0;"><div style="margin-left:-200px;width:450px;top:30%;background:#fff;position:fixed;left:50%;border-radius:4px;overflow:hidden;"><div style="height:40px;line-height:40px;background:${background};padding-left:10px;font-size:14px;color:#fff;"><i data-id="close" style="width:40px;float:right;text-align:center;cursor:pointer;font-size:18px;" title="close">${icon_close}</i><span>${title}</span></div><div style="margin:35px;text-align:center;font-size:14px;color:#666;">${content}</div><div style="margin:35px;font-size:14px;text-align:center;"><input type="button" data-id="ok" style="background:${background};width:100px;height:30px;line-height:30px;border:none;border-radius:4px;cursor:pointer;color:#fff;" value="${btn_label}"></div></div></div>`;
	return new Promise<void>((resolve) => {
		const container = window.document.createElement('div');
		container.style.position = 'fixed';
		container.style.zIndex = z_index();
		window.document.body.appendChild(container);
		container.insertAdjacentHTML('beforeend', html);
		const ok = container.querySelector<HTMLInputElement>('[data-id=ok]')!;
		const close = container.querySelector<HTMLDivElement>('[data-id=close]')!;
		const h1 = on(ok, 'click', destroy);
		const h2 = on(close, 'click', destroy);
		const h3 = on(window, 'keydown', (e: KeyboardEvent) => {
			if (e.keyCode === 27) {
				destroy();
			}
		});
		function destroy() {
			h1.destroy();
			h2.destroy();
			h3.destroy();
			window.document.body.removeChild(container);
			resolve();
		}
	});
}
